package com.swordget.runnable;

import com.swordget.util.EnvUitl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.concurrent.Callable;

/**
 * @Author: David
 * @Date: Created in 11:02 2020/4/21
 * @Description: ${DESCRIPTION}
 * @Modified By:
 * @Version: ${VERSION}
 */
public class InsertRunnable implements Callable<Boolean> {

    private Connection connection;



    /**
     * 执行插入的表名
     */
    private String tableName;

    /**
     * 要插入的数据 【行】【列】
     */
    private String[][] dataArray;

    /**
     * 插入数据的列结构
     */
    private List<String> columns;

    /**
     * 偏移量
     */
    private int offset;

    private String loginId;

    private String importId;

    private final Logger log = LoggerFactory.getLogger(InsertRunnable.class);


    public InsertRunnable(Connection connection, String tableName, String[][] dataArray, List<String> columns, int offset, String loginId, String importId) {
        this.connection = connection;
        this.tableName = tableName;
        this.dataArray = dataArray;
        this.columns = columns;
        this.offset = offset;
        this.loginId = loginId;
        this.importId = importId;
    }

    @Override
    public Boolean call() throws SQLException {
        log.info("================== 线程" + Thread.currentThread().getName() + "开始执行数据插入 ================");
        long start = System.currentTimeMillis();
        //添加隐藏列
        final List<String> newColumns = new ArrayList<>();
        newColumns.addAll(columns);
        //先把一些业务字段干掉，然后按顺序添加，保证顺序
        newColumns.addAll(Arrays.asList(new String[]{"SERIALNO", "CREATEDATE", "CREATETIME", "CREATEUSER", "IMPORTID",
                "HANDLEDATE", "HANDLETIME", "HANDLEUSER", "STATUS", "DATASOURCE"}));

        final String column = String.join(",", newColumns);
        final SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");
        final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        String handleDate = dayFormat.format(new Date());
        String handleTime = timeFormat.format(new Date());
        Connection conn = connection;
        try (Statement statement = conn.createStatement()) {
            //conn = dataSource.getConnection();
            for (int i = 0; i < offset; i++) {
                String[] data = dataArray[i];
                String values = String.join(",", data);
                StringBuilder commandBuilder = new StringBuilder();
                commandBuilder.append("INSERT INTO ");
                commandBuilder.append(tableName);
                commandBuilder.append(" (");
                commandBuilder.append(column);
                commandBuilder.append(") VALUES(");
                commandBuilder.append(values);
                commandBuilder.append(",'");
                commandBuilder.append(System.currentTimeMillis() +
                        String.format("%06d", Math.round(Math.random() * 1000000)) + String.format("%06d", i));
                commandBuilder.append("','");
                commandBuilder.append(handleDate);
                commandBuilder.append("','");
                commandBuilder.append(handleTime);
                commandBuilder.append("','");
                commandBuilder.append(loginId);
                commandBuilder.append("','");
                commandBuilder.append(importId);
                commandBuilder.append("','");
                commandBuilder.append(handleDate);
                commandBuilder.append("','");
                commandBuilder.append(handleTime);
                commandBuilder.append("','");
                commandBuilder.append(loginId);
                commandBuilder.append("','");
                commandBuilder.append("0");
                commandBuilder.append("','");
                commandBuilder.append("文件导入");
                commandBuilder.append("')");
                statement.addBatch(commandBuilder.toString());
            }
            statement.executeBatch();
            long end = System.currentTimeMillis();
            log.info("=================  线程" + Thread.currentThread().getName() + "插入完成，用时：" + (end - start) + " ===============" );
            return true;
        } catch (Exception e) {
            log.error("================= 线程" + Thread.currentThread().getName() + "执行过程中出现异常 =============", e);
        }
        return false;
    }
}
